<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    // 使用
    let promise = new Promise((resolve, reject) => {
      if (true) {
        resolve('成功')
      } else {
        reject('失败')
      }
    })
    promise.then(res => {
      // success
    }, err => {
      // error
    })

    /* 模拟promise */
    function myPromise(constructor) {
      let self = this;
      self.status = 'pending'; // 状态
      self.value = undefined; // 成功结果
      self.reason = undefined; // 失败原因

      function resolve (value) {
        if (self.status === 'pending') {
          self.status = 'fulfilled';
          self.value = value;
        }
      }
      function reject(reason) {
        if (self.status === 'pending') {
          self.status = 'rejected';
          self.reason = reason;
        }
      }

      // 捕获构造异常
      try {
        constructor(resolve, reject);
      } catch (error) {
        console.log(error, 'error');
      }
    }

    myPromise.prototype.then = function(onFulfilled, onRejected) {
      let self = this;
      switch (self.status) {
        case 'fulfilled':
          onFulfilled(self.value);
          break;
        case 'rejected':
          onRejected(self.reason);
          break;
        default:
          break;
      }
    }

    let p = new MyPromise((resolve, reject) => {
      resolve('成功');
    })
    p.then(res => {
      console.log(res, 'res');
    }, err => {
      console.log(err, 'err');
    })
  </script>
</body>
</html>